package fun.codedesign.yinxue.util;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

public class FileUtil {

    public static String readText(File file) {
        BufferedReader reader = null;
        StringBuilder builder = new StringBuilder();
        try {
            reader = new BufferedReader(new InputStreamReader(Files.newInputStream(file.toPath()), StandardCharsets.UTF_8));
            String line = "";
            while ((line = reader.readLine()) != null) {
                builder.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return builder.toString();
    }

    public static void writeText(File file, String text) {
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(file.toPath()), StandardCharsets.UTF_8));
            writer.write(text);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void deleteAllFile(File file) {
        doDelete(file);
    }

    private static void doDelete(File file) {
        if (file.isFile()) {
            boolean flag = file.delete();
            System.out.println(flag);
        } else if (file.isDirectory()) {
            File[] childFiles = file.listFiles();
            for (File childFile : childFiles) {
                doDelete(childFile);
            }
            // 最后删除空目录的自己
            if (childFiles.length == 0) {
                boolean flag2 = file.delete();
                System.out.println(flag2);
            }
        }
        // 跳出递归后，删除自身空文件夹
        if (file.isDirectory()) {
            boolean flag3 = file.delete();
            System.out.println(flag3);
        }
    }

    public static File newFile(File parentFile, String fileName) {
        File newFile = new File(parentFile, fileName);
        try {
            System.out.println(newFile.createNewFile());
            return newFile;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static File newDir(File parentFile, String dirName) {
        String name = "新建文件夹";
        File newDir = new File(parentFile, dirName);
        System.out.println(newDir.mkdir());
        return newDir;
    }
}
